using AvalonAdmin.BaseViewModel;
using AvalonAdmin.BaseControl;
using AvalonAdmin.Consts;
using AvalonAdmin.Helpers;
using AvalonAdminDto.Common;
using AvalonAdminDto.Base;
using AvalonAdmin.Converters;
using AvalonAdminDto.Rule.RuleConfigDtos;
using AvalonAdminDto.Sys.AdminDtos;
using AvalonAdminDto.CarType.AreaDtos;
using AvalonAdminDto.CarType.BrandDtos;
using AvalonAdminDto.CarType.CountryDtos;
using AvalonAdminDto.CarType.CarTypeDtos;
using AvalonAdminDto.CarType.CarTypeVersionDtos;
using AvalonAdminDto.CarType.VehicleSeriesDtos;
using AvalonAdminDto.CarParts.CarPartsDtos;
using AvalonAdminDto.CarParts.CarPartsTypeDtos;
using AvalonAdminDto.CarParts.VehicleSeriesCarPartsTypeDtos;
using System.Collections.ObjectModel;
using System.Data;
using System.IO;
using System.Reflection;
using System.Text;
using System.Globalization;
using System.Windows.Input;
using CommunityToolkit.Mvvm.Input;
using Avalonia.Platform.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls;
using D.Util.UtilExcel;
using Flurl.Http;

namespace AvalonAdmin.Pages.Common.ViewModels
{
    /// <summary>
    /// 数据导入功能的ViewModel
    /// </summary>
    public class ImportViewModel : Base
    {
        #region 字段和属性
        private readonly ImportType _importType;                // 当前导入类型
        private readonly Dictionary<string, string> _importModelDic;  // 列名与模型属性的映射字典
        private readonly BaseUserControl _owner;                     // 所属页面引用
        //private readonly Dictionary<ImportType, string> _fileNames;  // 导入类型对应的模板文件名

        // 数据集合，用于DataGrid显示
        private ObservableCollection<object> _data;
        public ObservableCollection<object> Data
        {
            get => _data;
            set => SetProperty(ref _data, value);
        }

        // DataGrid列定义集合
        private ObservableCollection<DataGridColumnInfo> _columns;
        public ObservableCollection<DataGridColumnInfo> Columns
        {
            get => _columns;
            set => SetProperty(ref _columns, value);
        }

        // 选择的Excel文件路径
        private string? _filePath;
        public string? FilePath
        {
            get => _filePath;
            set => SetProperty(ref _filePath, value);
        }

        // 状态提示信息
        private string _statusMessage = "请选择Excel文件开始导入";
        public string StatusMessage
        {
            get => _statusMessage;
            set => SetProperty(ref _statusMessage, value);
        }

        // 导入统计信息
        private int _totalCount;
        public int TotalCount
        {
            get => _totalCount;
            set => SetProperty(ref _totalCount, value);
        }

        private int _successCount;
        public int SuccessCount
        {
            get => _successCount;
            set => SetProperty(ref _successCount, value);
        }

        private int _errorCount;
        public int ErrorCount
        {
            get => _errorCount;
            set => SetProperty(ref _errorCount, value);
        }

        // 是否允许导入的标志
        private bool _canImport;
        public bool CanImport
        {
            get => _canImport;
            set => SetProperty(ref _canImport, value);
        }
        #endregion

        #region 构造函数
        /// <summary>
        /// 初始化ImportViewModel实例
        /// </summary>
        /// <param name="owner">所属页面</param>
        /// <param name="id">可选ID参数</param>
        /// <param name="viewStatus">视图状态</param>
        /// <param name="importType">导入类型</param>
        public ImportViewModel(BaseUserControl owner, string? id, ViewStatus? viewStatus, ImportType importType)
            : base()
        {
            _owner = owner;
            _importType = importType;
            // 加载指定导入类型的模型字典映射
            _importModelDic = TextConvert.LoadModelDic(importType);
            Console.WriteLine($"[DEBUG] ImportViewModel构造函数 - ImportType: {importType}");
            Console.WriteLine($"[DEBUG] ImportViewModel构造函数 - _importModelDic是否为null: {_importModelDic == null}");
            if (_importModelDic != null)
            {
                Console.WriteLine($"[DEBUG] ImportViewModel构造函数 - _importModelDic包含{_importModelDic.Count}个映射");
                foreach (var kvp in _importModelDic)
                {
                    Console.WriteLine($"[DEBUG] 映射: {kvp.Key} -> {kvp.Value}");
                }
            }

            // 初始化不同导入类型的模板文件名
            //_fileNames = new Dictionary<ImportType, string>()
            //{
            //    { ImportType.VehicleSeries, "车系.csv" },
            //    { ImportType.CarType, "车型.csv" }
            //};

            // 初始化集合
            Data = new ObservableCollection<object>();
            Columns = new ObservableCollection<DataGridColumnInfo>();

            // 根据模型字典创建DataGrid列
            if (_importModelDic != null && _importModelDic.Any())
            {
                CreateColumns(_importModelDic);
            }

            // 初始化命令
            InitializeCommands();
        }
        #endregion

        #region 命令初始化
        /// <summary>
        /// 初始化视图使用的命令
        /// </summary>
        private void InitializeCommands()
        {
            SelectExcelCommand = new RelayCommand(SelectExcel);
            //DownloadTemplateCommand = new RelayCommand(DownloadTemplate);
            ClearDataCommand = new RelayCommand(ClearData);
            SubmitCommand = new RelayCommand(Submit);
        }

        // 命令属性
        public ICommand SelectExcelCommand { get; private set; }      // 选择Excel文件命令
        //public ICommand DownloadTemplateCommand { get; private set; } // 下载模板命令
        public ICommand ClearDataCommand { get; private set; }        // 清除数据命令
        public ICommand SubmitCommand { get; private set; }           // 提交数据命令
        #endregion

        #region 基类方法
        /// <summary>
        /// 加载数据方法（导入页面不需要）
        /// </summary>
        protected async void LoadData()
        {
            // 导入页面不需要加载数据
        }

        /// <summary>
        /// 提交导入的数据到服务器
        /// </summary>
        protected async void Submit()
        {
            if (Data == null || !Data.Any())
            {
                ShowWarning("没有可导入的数据");
                return;
            }

            IsLoading = true;
            StatusMessage = "正在导入数据...";

            try
            {
                // 根据导入类型调用相应的保存方法
                switch (_importType)
                {
                    case ImportType.Admin:
                        await SaveData<RepImpAdmin>(ApiUrl.AddAdmin, ApiUrl.UpdateAdmin);
                        break;
                    case ImportType.Area:
                        await SaveData<RepImpArea>(ApiUrl.AddArea, ApiUrl.UpdateArea);
                        break;
                    case ImportType.Brand:
                        await SaveData<RepImpBrand>(ApiUrl.AddBrand, ApiUrl.UpdateBrand);
                        break;
                    case ImportType.Country:
                        await SaveData<RepImpCountry>(ApiUrl.AddCountry, ApiUrl.UpdateCountry);
                        break;
                    case ImportType.Car:
                        // Car类型暂时不支持，需要后端API支持
                        ShowWarning("Car类型导入功能暂未实现");
                        return;
                    case ImportType.CarType:
                        await SaveData<RepImpCarType>(ApiUrl.AddCarType, ApiUrl.UpdateCarType);
                        break;
                    case ImportType.CarTypeVersion:
                        await SaveData<RepImpCarTypeVersion>(ApiUrl.AddCarTypeVersion, ApiUrl.UpdateCarTypeVersion);
                        break;
                    case ImportType.PreciseCartType:
                        // PreciseCartType类型暂时不支持，需要后端API支持
                        ShowWarning("PreciseCartType类型导入功能暂未实现");
                        return;
                    case ImportType.SalesCarType:
                        // SalesCarType类型暂时不支持，需要后端API支持
                        ShowWarning("SalesCarType类型导入功能暂未实现");
                        return;
                    case ImportType.VehicleSeries:
                        await SaveData<RepImpVehicleSeries>(ApiUrl.AddVehicleSeries, ApiUrl.UpdateVehicleSeries);
                        break;
                    case ImportType.CarParts:
                        await SaveData<RepImpCarParts>(ApiUrl.AddCarParts, ApiUrl.UpdateCarParts);
                        break;
                    case ImportType.CarPartsType:
                        await SaveData<RepImpCarPartsType>(ApiUrl.AddCarPartsType, ApiUrl.UpdateCarPartsType);
                        break;
                    case ImportType.VehicleSeriesCarPartsType:
                        await SaveData<RepImpVehicleSeriesCarPartsType>(ApiUrl.AddVehicleSeriesCarPartsType, ApiUrl.UpdateVehicleSeriesCarPartsType);
                        break;
                    case ImportType.Rule:
                        await SaveData<RepImpRuleConfig>(ApiUrl.AddRuleConfig, ApiUrl.UpdateRuleConfig);
                        break;
                    default:
                        ShowWarning($"不支持的导入类型：{_importType}");
                        return;
                }

                UpdateStatistics();
                StatusMessage = $"导入完成！成功：{SuccessCount}，失败：{ErrorCount}";
                CanImport = false; // 导入完成后禁用导入按钮，防止重复导入
                ShowSuccess("数据导入完成");
            }
            catch (Exception ex)
            {
                StatusMessage = "导入失败";
                CanImport = false; // 导入失败时禁用导入按钮
                ShowError($"导入过程中发生错误：{ex.Message}");
            }
            finally
            {
                IsLoading = false;
            }
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 创建DataGrid列
        /// </summary>
        /// <param name="keyValuePairs">列名与属性的映射字典</param>
        private void CreateColumns(Dictionary<string, string> keyValuePairs)
        {
            Columns.Clear();
            foreach (var item in keyValuePairs)
            {
                Columns.Add(new DataGridColumnInfo { Header = item.Key, BindingPath = item.Value });
            }
        }

        /// <summary>
        /// 选择Excel文件
        /// </summary>
        private async void SelectExcel()
        {
            try
            {
                var topLevel = TopLevel.GetTopLevel(_owner);
                if (topLevel != null)
                {
                    var files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
                    {
                        Title = "选择Excel或CSV文件",
                        AllowMultiple = false,
                        FileTypeFilter = new[]
                        {
                            new FilePickerFileType("Excel文件") { Patterns = new[] { "*.xlsx", "*.xls" } },
                            new FilePickerFileType("CSV文件") { Patterns = new[] { "*.csv" } },
                            FilePickerFileTypes.All
                        }
                    });

                    if (files.Count > 0)
                    {
                        string filePath = files[0].Path.LocalPath;
                        FilePath = filePath;
                        string extension = Path.GetExtension(filePath).ToLower();
                        
                        if (extension == ".xlsx" || extension == ".xls")
                        {
                            StatusMessage = "正在读取Excel文件...";
                            await LoadExcelData(filePath);
                        }
                        else if (extension == ".csv")
                        {
                            StatusMessage = "正在读取CSV文件...";
                            await LoadCsvData(filePath);
                        }
                        else
                        {
                            ShowError("不支持的文件格式，请选择Excel(.xlsx/.xls)或CSV(.csv)文件！");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError($"选择文件时发生错误：{ex.Message}");
            }
        }

        /// <summary>
        /// 加载CSV数据
        /// </summary>
        /// <param name="filePath">文件路径</param>
        private async Task LoadCsvData(string filePath)
        {
            try
            {
                if (_importModelDic.Count <= 0)
                {
                    ShowError($"读取CSV文件时无对比文件!");
                    return;
                }
                IsLoading = true;
                Data.Clear();

                Console.WriteLine($"[DEBUG] 开始读取文件: {filePath}");
                var excelDataSet = UtilExcel.FileToDataSet(filePath);
                Console.WriteLine($"[DEBUG] 文件读取完成，数据表数量: {excelDataSet.Tables.Count}");
                
                if (excelDataSet.Tables.Count > 0)
                {
                    var table = excelDataSet.Tables[0];
                    Console.WriteLine($"[DEBUG] 第一个数据表行数: {table.Rows.Count}, 列数: {table.Columns.Count}");
                    
                    await DatatableToModel(excelDataSet.Tables[0]);
                    CanImport = false; // 文件读取完成后，需要先验证数据才能导入
                    UpdateStatistics();
                    StatusMessage = $"文件读取完成，共{TotalCount}条数据，请等待数据验证完成";
                    Console.WriteLine($"[DEBUG] 数据处理完成，TotalCount: {TotalCount}, Data.Count: {Data.Count}");
                }
                else
                {
                    StatusMessage = "Excel文件中没有找到数据";
                    ShowWarning("Excel文件中没有找到数据");
                    Console.WriteLine($"[DEBUG] Excel文件中没有找到数据表");
                }
            }
            catch (Exception ex)
            {
                StatusMessage = "文件读取失败";
                ShowError($"读取Excel文件时发生错误：{ex.Message}");
            }
            finally
            {
                IsLoading = false;
            }
        }

        /// <summary>
        /// 加载Excel数据
        /// </summary>
        /// <param name="filePath">文件路径</param>
        private async Task LoadExcelData(string filePath)
        {
            try
            {
                if (_importModelDic.Count <= 0)
                {
                    ShowError($"读取Excel文件时无对比文件!");
                    return;
                }
                IsLoading = true;
                Data.Clear();

                Console.WriteLine($"[DEBUG] 开始读取Excel文件: {filePath}");
                var excelDataSet = UtilExcel.FileToDataSet(filePath);
                Console.WriteLine($"[DEBUG] Excel文件读取完成，数据表数量: {excelDataSet.Tables.Count}");
                
                if (excelDataSet.Tables.Count > 0)
                {
                    var table = excelDataSet.Tables[0];
                    Console.WriteLine($"[DEBUG] 第一个数据表行数: {table.Rows.Count}, 列数: {table.Columns.Count}");
                    
                    await DatatableToModel(excelDataSet.Tables[0]);
                    CanImport = false; // 文件读取完成后，需要先验证数据才能导入
                    UpdateStatistics();
                    StatusMessage = $"文件读取完成，共{TotalCount}条数据，请等待数据验证完成";
                    Console.WriteLine($"[DEBUG] 数据处理完成，TotalCount: {TotalCount}, Data.Count: {Data.Count}");
                }
                else
                {
                    StatusMessage = "Excel文件中没有找到数据";
                    ShowWarning("Excel文件中没有找到数据");
                    Console.WriteLine($"[DEBUG] Excel文件中没有找到数据表");
                }
            }
            catch (Exception ex)
            {
                StatusMessage = "文件读取失败";
                ShowError($"读取Excel文件时发生错误：{ex.Message}");
            }
            finally
            {
                IsLoading = false;
            }
        }

        /// <summary>
        /// 下载导入模板
        /// </summary>
        //private async void DownloadTemplate()
        //{
        //    try
        //    {
        //        var topLevel = TopLevel.GetTopLevel(_owner);
        //        if (topLevel != null)
        //        {
        //            string suggestedFileName = _fileNames.ContainsKey(_importType) ? _fileNames[_importType] : "template.csv";

        //            var file = await topLevel.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
        //            {
        //                Title = "保存模板文件",
        //                SuggestedFileName = suggestedFileName,
        //                DefaultExtension = "csv",
        //                FileTypeChoices = new[]
        //                {
        //                    new FilePickerFileType("Excel文件") { Patterns = new[] { "*.csv" } }
        //                }
        //            });

        //            if (file != null)
        //            {
        //                string result = file.Path.LocalPath;
        //                string templatePath = Path.Combine("Resources", "Template", _fileNames[_importType]);

        //                if (!File.Exists(templatePath))
        //                {
        //                    ShowError("模板文件不存在！");
        //                    return;
        //                }

        //                using (var fileStream = new FileStream(templatePath, FileMode.Open, FileAccess.Read))
        //                {
        //                    IWorkbook workbook = new XSSFWorkbook(fileStream);
        //                    using (var newFileStream = new FileStream(result, FileMode.Create, FileAccess.Write))
        //                    {
        //                        workbook.Write(newFileStream);
        //                    }
        //                }

        //                ShowSuccess("模板下载成功！");
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        ShowError($"下载模板时发生错误：{ex.Message}");
        //    }
        //}

        /// <summary>
        /// 清除已加载的数据
        /// </summary>
        private void ClearData()
        {
            Data.Clear();
            FilePath = string.Empty;
            CanImport = false;
            TotalCount = 0;
            SuccessCount = 0;
            ErrorCount = 0;
            StatusMessage = "请选择Excel文件开始导入";
        }

        /// <summary>
        /// 将DataTable转换为模型
        /// </summary>
        /// <param name="dt">数据表</param>
        private async Task DatatableToModel(DataTable dt)
        {
            switch (_importType)
            {
                case ImportType.Admin:
                    await ToModel<RepImpAdmin>(dt, ApiUrl.CheckImportAdmin);
                    break;
                case ImportType.Area:
                    await ToModel<RepImpArea>(dt, ApiUrl.CheckImportArea);
                    break;
                case ImportType.Brand:
                    await ToModel<RepImpBrand>(dt, ApiUrl.CheckImportBrand);
                    break;
                case ImportType.Country:
                    await ToModel<RepImpCountry>(dt, ApiUrl.CheckImportCountry);
                    break;
                case ImportType.Car:
                    //await ToModel<RepImpCar>(dt, ApiUrl.CheckImportCar);
                    break;
                case ImportType.CarType:
                    await ToModel<RepImpCarType>(dt, ApiUrl.CarTypeCheckImpData);
                    break;
                case ImportType.CarTypeVersion:
                    await ToModel<RepImpCarTypeVersion>(dt, ApiUrl.CheckImportCarTypeVersion);
                    break;
                case ImportType.PreciseCartType:
                    //await ToModel<RepImpPreciseCartType>(dt, ApiUrl.CheckImportPreciseCartType);
                    break;
                case ImportType.SalesCarType:
                    //await ToModel<RepImpSalesCarType>(dt, ApiUrl.CheckImportSalesCarType);
                    break;
                case ImportType.VehicleSeries:
                    await ToModel<RepImpVehicleSeries>(dt, ApiUrl.VehicleSeriesCheckImpData);
                    break;
                case ImportType.CarParts:
                    await ToModel<RepImpCarParts>(dt, ApiUrl.CheckImportCarParts);
                    break;
                case ImportType.CarPartsType:
                    await ToModel<RepImpCarPartsType>(dt, ApiUrl.CheckImportCarType);
                    break;
                case ImportType.VehicleSeriesCarPartsType:
                    await ToModel<RepImpVehicleSeriesCarPartsType>(dt, ApiUrl.CheckImportVehicleSeriesCarPartsType);
                    break;
                case ImportType.Rule:
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 将数据行转换为指定模型
        /// </summary>
        /// <typeparam name="T">模型类型</typeparam>
        /// <param name="dt">数据表</param>
        /// <param name="url">验证数据的API地址</param>
        private async Task ToModel<T>(DataTable dt, string url) where T : BaseImpModel
        {
            //var allModels = new List<T>();
            Console.WriteLine($"[DEBUG] ToModel开始处理，数据表行数: {dt.Rows.Count}");
            Console.WriteLine($"[DEBUG] 当前Data集合数量: {Data.Count}");

            foreach (DataRow dr in dt.Rows)
            {
                T model = RowDataToModel<T>(dr, dt.Columns, _importModelDic);
                if (model != null)
                {
                    //ConvertSelectItem(model);
                    //allModels.Add(model);
                    Data.Add(model);
                    Console.WriteLine($"[DEBUG] 添加模型到Data集合，当前总数: {Data.Count}");
                }
            }

            // 如果没有数据，直接返回
            if (!Data.Any())
            {
                StatusMessage = "没有找到有效数据";
                CanImport = false;
                Console.WriteLine($"[DEBUG] 没有找到有效数据，Data集合为空");
                return;
            }
            
            Console.WriteLine($"[DEBUG] 数据转换完成，Data集合最终数量: {Data.Count}");

            try
            {
                var res = await HttpHelper<List<T>>.PostAsync(url, Data);
                if (res.Code == D.UtilCore.Dtos.StatusCodeEnum.OK)
                {
                    StatusMessage = "数据验证成功！可以开始导入";
                    ShowWarning("数据验证成功！");
                    CanImport = true; // 验证成功后启用导入按钮
                }
                else
                {
                    StatusMessage = "数据验证失败，请检查数据格式";
                    ShowWarning("数据验证失败，请检查数据格式");
                    CanImport = false; // 验证失败时禁用导入按钮
                }
            }
            catch (Exception ex)
            {
                StatusMessage = "数据验证失败，请检查数据格式";
                ShowError($"数据验证失败，请检查数据格式{ex.Message}");
                CanImport = false; // 异常时禁用导入按钮
            }
        }

        /// <summary>
        /// 转换选择项（如销售状态、车辆类型等）
        /// </summary>
        /// <typeparam name="T">模型类型</typeparam>
        /// <param name="obj">模型实例</param>
        //private void ConvertSelectItem<T>(T obj)
        //{
        //    if (_importType == ImportType.VehicleSeries && obj is RepImpVehicleSeries vehicleSeriesModel)
        //    {
        //        vehicleSeriesModel.SaleStatus = TextConvert.ConvertSaleStatus(vehicleSeriesModel.SaleStatusText);
        //    }
        //    else if (_importType == ImportType.CarType && obj is RepImpCarType carTypeModel)
        //    {
        //        carTypeModel.VehicleType = TextConvert.ConvertVehicleType(carTypeModel.VehicleTypeText);
        //    }
        //}

        /// <summary>
        /// 将数据行转换为模型对象
        /// </summary>
        /// <typeparam name="T">模型类型</typeparam>
        /// <param name="dr">数据行</param>
        /// <param name="dataColumn">数据列集合</param>
        /// <param name="modelDic">模型字典映射</param>
        /// <returns>转换后的模型对象</returns>
        private T RowDataToModel<T>(DataRow dr, DataColumnCollection dataColumn, Dictionary<string, string> modelDic) where T : BaseImpModel
        {
            Type objectType = typeof(T);
            object objectInstance = Activator.CreateInstance(objectType);
            StringBuilder errorStringBuilder = new StringBuilder();

            try
            {
                foreach (DataColumn col in dataColumn)
                {
                    if (modelDic.ContainsKey(col.ColumnName))
                    {
                        PropertyInfo propertyInfo = objectType.GetProperty(modelDic[col.ColumnName]);

                        if (propertyInfo != null && propertyInfo.CanWrite)
                        {
                            string value = dr[col.ColumnName]?.ToString();
                            if (!string.IsNullOrWhiteSpace(value))
                            {
                                if (propertyInfo.PropertyType == typeof(DateTime) || propertyInfo.PropertyType == typeof(DateTime?))
                                {
                                    if (DateTime.TryParseExact(value, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date))
                                    {
                                        propertyInfo.SetValue(objectInstance, date);
                                    }
                                    else
                                    {
                                        errorStringBuilder.Append($"【{col.ColumnName}】转换日期格式失败!");
                                    }
                                }
                                else if (propertyInfo.PropertyType == typeof(bool) || propertyInfo.PropertyType == typeof(bool?))
                                {
                                    // 处理布尔类型转换
                                    if (bool.TryParse(value, out bool boolValue))
                                    {
                                        propertyInfo.SetValue(objectInstance, boolValue);
                                    }
                                    else
                                    {
                                        // 尝试其他常见的布尔值表示方式
                                        string lowerValue = value.ToLower().Trim();
                                        if (lowerValue == "1" || lowerValue == "是" || lowerValue == "yes" || lowerValue == "y" || lowerValue == "启用" || lowerValue == "true")
                                        {
                                            propertyInfo.SetValue(objectInstance, true);
                                        }
                                        else if (lowerValue == "0" || lowerValue == "否" || lowerValue == "no" || lowerValue == "n" || lowerValue == "禁用" || lowerValue == "false")
                                        {
                                            propertyInfo.SetValue(objectInstance, false);
                                        }
                                        else
                                        {
                                            errorStringBuilder.Append($"【{col.ColumnName}】布尔值转换失败，无法识别的值: {value}!");
                                        }
                                    }
                                }
                                else
                                {
                                    propertyInfo.SetValue(objectInstance, value);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errorStringBuilder.Append(ex.Message);
            }

            T returnT = (T)objectInstance;
            if (errorStringBuilder.Length > 0)
            {
                returnT.ErrorMessage = errorStringBuilder.ToString();
                returnT.IsError = true;
            }

            // 根据Id字段判断是新增还是修改
            // 如果Id有值，则为修改操作；如果Id为空，则为新增操作
            if (!string.IsNullOrWhiteSpace(returnT.Id))
            {
                returnT.IsAdd = false; // 有Id表示修改
            }
            else
            {
                returnT.IsAdd = true;  // 无Id表示新增
            }

            return returnT;
        }

        /// <summary>
        /// 保存数据到服务器
        /// </summary>
        /// <typeparam name="T">模型类型</typeparam>
        /// <param name="addUrl">新增API地址</param>
        /// <param name="updateUrl">更新API地址</param>
        private async Task SaveData<T>(string addUrl, string updateUrl) where T : BaseImpModel
        {
            var newData = new ObservableCollection<object>();

            foreach (var item in Data)
            {
                if (item is T model && !model.IsError)
                {
                    try
                    {
                        var res = model.IsAdd
                            ? await HttpHelper<int>.PostAsync(addUrl, model)
                            : await HttpHelper<int>.PostAsync(updateUrl, model);

                        model.IsSuccess = res.Code == D.UtilCore.Dtos.StatusCodeEnum.OK;
                        model.ErrorMessage = res.Msg;
                    }
                    catch (FlurlHttpException httpEx)
                    {
                        model.IsSuccess = false;
                        var errorContent = await httpEx.GetResponseStringAsync();
                        model.ErrorMessage = $"HTTP错误 {httpEx.StatusCode}: {errorContent ?? httpEx.Message}";
                    }
                    catch (Exception ex)
                    {
                        model.IsSuccess = false;
                        model.ErrorMessage = ex.Message;
                    }
                }
                newData.Add(item);
            }

            Data = newData;
        }

        /// <summary>
        /// 更新导入统计信息
        /// </summary>
        private void UpdateStatistics()
        {
            TotalCount = Data.Count;
            SuccessCount = Data.OfType<BaseImpModel>().Count(x => x.IsSuccess);
            ErrorCount = Data.OfType<BaseImpModel>().Count(x => x.IsError || !x.IsSuccess);
        }
        #endregion
    }

    /// <summary>
    /// DataGrid列信息
    /// </summary>
    public class DataGridColumnInfo
    {
        public string Header { get; set; }       // 列标题
        public string BindingPath { get; set; }  // 绑定路径
    }
}